package com.sayice.coursetable.ui.music;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.work.impl.model.PreferenceDao;

import com.sayice.coursetable.MainActivity;
import com.sayice.coursetable.R;
import com.sayice.coursetable.logic.dao.PreferencesDao;
import com.sayice.coursetable.logic.utils.MusicUtils;

/**
 * 音乐适配器
 */
public class MusicAdapter extends RecyclerView.Adapter<MusicAdapter.ViewHolder> {
    private final String[] musics;

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
        }
    }

    public MusicAdapter(@NonNull String[] musics) {
        this.musics = musics;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(viewGroup.getContext());
        View view = layoutInflater.inflate(R.layout.music_item, viewGroup, false);
        ViewHolder viewHolder = new ViewHolder(view);
        viewHolder.itemView.setOnTouchListener((v, event) -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    int position = viewHolder.getBindingAdapterPosition();
                    String music = musics[position];
                    MainActivity mainActivity = (MainActivity) viewGroup.getContext();
//                    mainActivity.playMusic(MusicUtils.midi(PreferencesDao.getMidiNum())
//                            + "-" + music + ".mp3");
                    mainActivity.playMusic(music + ".mp3");
                    break;
                case MotionEvent.ACTION_UP:
                    v.performClick();
                    break;
                default:
                    break;
            }
            return false;
        });
        viewHolder.itemView.setOnClickListener(view1 -> {
            Log.d("MusicAdapter", "item clicked");
        });
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

    }

    @Override
    public int getItemCount() {
        return musics.length;
    }
}
